﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Zhaoxi.NET6.Interfaces;

namespace NET6Demo.WebApi.Utility.Filters
{
    /// <summary>
    /// CustomAsyncExceptionFilterAttribute
    /// </summary>
    public class CustomAsyncExceptionFilterAttribute : Attribute, IAsyncExceptionFilter
    {
        /// <summary>
        /// 发生异常后就在这里处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            //在这里就应该处理异常
            if (context.ExceptionHandled == false) //如果没有被处理
            {
                context.Result = new JsonResult(new ApiResult<object>()
                {
                    Success = false,
                    Message = context.Exception.Message
                });
                //就在这里处理
                context.ExceptionHandled = true;//异常已经被处理过了；
            }

            await Task.CompletedTask;
        }
    }
}
